import {
	PRINTER_RECORD_KEY,
	PRINTER_INFO_KEY,
	PRINTER_PAPER_SIZE_KEY,
	PRINTER_PAPER_GAP_KEY,
	PRINTER_PAPER_BLINE_KEY,
	connectionModes
} from '@/utils/printer/index.d';
import {
	isArray
} from '@/utils/is';
import {
	onBluetoothDeviceState
} from '@/utils/bluetooth/index';
import jarvisConnected from '@/static/audio/jarvis_connected.wav';
import jarvisDisconnected from '@/static/audio/jarvis_disconnected.wav';
import {
	useI18n
} from "@/locales/setupI18n";

export const state = {
	/** 打印机记录，打印机信息集合 */
	printerRecord: [],
	/** 打印机信息 */
	printerInfo: {
		name: '', // (String 类型 )蓝牙设备名称 某些设备可能没有此字段值。
		deviceId: '', //  (String 类型 )蓝牙设备的id
		RSSI: 0, //  (Number 类型 )蓝牙设备的信号强度
		advertisData: null, //  (ArrayBuffer 类型 )蓝牙设备的广播数据段中的ManufacturerData数据段
		advertisServiceUUIDs: [], //  (Array[String] 类型 )蓝牙设备的广播数据段中的ServiceUUIDs数据段
		localName: '', //  (String 类型 )蓝牙设备的广播数据段中的LocalName数据段
		serviceData: {}, //  (JSON 类型 )蓝牙设备的广播数据段中的ServiceData数据段

		sevices: [], //  蓝牙设备所有服务(service)
		characteristics: [], //  蓝牙设备的所有服务的所有特征值(characteristic)

		connected: false, //  是否已连接
		autoConnect: false, //  是否自动连接

		readServiceId: '', //  read 操作 蓝牙设备服务的 uuid
		readCharaterId: '', //  read 操作 蓝牙设备特征值的 uuid
		writeServiceId: '', //  write 操作 蓝牙设备服务的 uuid
		writeCharaterId: '', //  write 操作 蓝牙设备特征值的 uuid
		notifyServiceId: '', //  notify 操作 蓝牙设备服务的 uuid
		notifyCharaterId: '', //  notify 操作 蓝牙设备特征值的 uuid
		indicateServiceId: '', //  indicate 操作 蓝牙设备服务的 uuid
		indicateCharaterId: '', //  indicate 操作 蓝牙设备特征值的 uuid
	},
	/** 打印机纸张尺寸(mm) */
	printerPaperSize: null,
	/** 打印机纸张间距(mm) */
	printerPaperGap: null,
	/** 打印机纸张黑标(mm) */
	printerPaperBline: null,
	/** 打印机连接方式： BLUETOOTH - 蓝牙、WIFI - 无线热点、WIRED - 有线连接 */
	PrinterConnectionMode: '',
}

/** 获取器 */
export const getters = {
	/** 获取打印机记录 */
	getPrinterRecord: (state, getters, dispatch) => {
		if (state.printerRecord) {
			return state.printerRecord;
		}
		const printerRecord = uni.getStorageSync(PRINTER_RECORD_KEY);
		if (printerRecord) {
			state.printerRecord = printerRecord;
			return printerRecord;
		}
		return [];
	},
	/** 获取打印机信息 */
	getPrinterInfo: state => {
		if (state.printerInfo && state.printerInfo.deviceId && state.printerInfo.deviceId !== '') {
			return state.printerInfo;
		}
		state.printerInfo = uni.getStorageSync(PRINTER_INFO_KEY);
		return state.printerInfo;
	},
	/** 获取打印机纸张尺寸 */
	getPrinterPaperSize: state => {
		if (state.printerPaperSize !== undefined && state.printerPaperSize !== null &&
			state.printerPaperSize !== '') {
			if (state.printerPaperSize.Width === undefined || state.printerPaperSize.Width === null ||
				state.printerPaperSize.Width === '') {
				state.printerPaperSize.Width = 0;
			}
			if (state.printerPaperSize.Height === undefined || state.printerPaperSize.Height === null ||
				state.printerPaperSize.Height === '') {
				state.printerPaperSize.Height = 0;
			}
			return state.printerPaperSize;
		}
		const paperSize = uni.getStorageSync(PRINTER_PAPER_SIZE_KEY);
		if (paperSize !== undefined && paperSize !== null && paperSize !== '') {
			if (paperSize.Width === undefined || paperSize.Width === null || paperSize.Width === '') {
				paperSize.Width = 0;
			}
			if (paperSize.Height === undefined || paperSize.Height === null || paperSize.Height === '') {
				paperSize.Height = 0;
			}
			state.printerPaperSize = paperSize;
		} else {
			state.printerPaperSize = {
				Width: 70,
				Height: 50
			};
		}
		return state.printerPaperSize;
	},
	/** 获取打印机纸张间距 */
	getPrinterPaperGap: state => {
		if (state.printerPaperGap !== undefined && state.printerPaperGap !== null &&
			state.printerPaperGap !== '') {
			if (state.printerPaperGap.M === undefined || state.printerPaperGap.M === null ||
				state.printerPaperGap.M === '') {
				state.printerPaperGap.M = 0;
			}
			if (state.printerPaperGap.N === undefined || state.printerPaperGap.N === null ||
				state.printerPaperGap.N === '') {
				state.printerPaperGap.N = 0;
			}
			return state.printerPaperGap;
		}
		const paperGap = uni.getStorageSync(PRINTER_PAPER_GAP_KEY);
		if (paperGap !== undefined && paperGap !== null && paperGap !== '') {
			if (paperGap.M === undefined || paperGap.M === null || paperGap.M === '') {
				paperGap.M = 0;
			}
			if (paperGap.N === undefined || paperGap.N === null || paperGap.N === '') {
				paperGap.N = 0;
			}
			state.printerPaperGap = paperGap;
		} else {
			state.printerPaperGap = {
				M: 0,
				N: 0
			};
		}
		return state.printerPaperGap;
	},
	/** 获取打印机纸张黑标 */
	getPrinterPaperBline: state => {
		if (state.printerPaperBline !== undefined && state.printerPaperBline !== null &&
			state.printerPaperBline !== '') {
			if (state.printerPaperBline.M === undefined || state.printerPaperBline.M === null ||
				state.printerPaperBline.M === '') {
				state.printerPaperBline.M = 0;
			}
			if (state.printerPaperBline.N === undefined || state.printerPaperBline.N === null ||
				state.printerPaperBline.N === '') {
				state.printerPaperBline.N = 0;
			}
			return state.printerPaperBline;
		}
		const paperBline = uni.getStorageSync(PRINTER_PAPER_BLINE_KEY);
		if (paperBline !== undefined && paperBline !== null && paperBline !== '') {
			if (paperBline.M === undefined || paperBline.M === null || paperBline.M === '') {
				paperBline.M = 0;
			}
			if (paperBline.N === undefined || paperBline.N === null || paperBline.N === '') {
				paperBline.N = 0;
			}
			state.printerPaperBline = paperBline;
		} else {
			state.printerPaperBline = {
				M: 0,
				N: 0
			};
		}
		return state.printerPaperBline;
	},
}

/** 方法 */
export const actions = {
	/** 添加打印机记录 */
	addPrinterRecord: function({
		state,
		commit,
		dispatch
	}, printerInfo) {
		let printerRecord = state.getPrinterRecord;
		if (printerRecord === undefined || printerRecord === null || isArray(printerRecord) === false) {
			printerRecord = [];
		}
		if (printerInfo) {
			const storagePrinterInfo = {
				name: printerInfo.name, // (String 类型 )蓝牙设备名称 某些设备可能没有此字段值。
				deviceId: printerInfo.deviceId, //  (String 类型 )蓝牙设备的id
				advertisData: printerInfo.advertisData, //  (ArrayBuffer 类型 )蓝牙设备的广播数据段中的ManufacturerData数据段
				advertisServiceUUIDs: printerInfo
					.advertisServiceUUIDs, //  (Array[String] 类型 )蓝牙设备的广播数据段中的ServiceUUIDs数据段
				localName: printerInfo.localName, //  (String 类型 )蓝牙设备的广播数据段中的LocalName数据段
				serviceData: printerInfo.serviceData, //  (JSON 类型 )蓝牙设备的广播数据段中的ServiceData数据段

				sevices: printerInfo.sevices, //  蓝牙设备所有服务(service)
				characteristics: printerInfo.characteristics, //  蓝牙设备的所有服务的所有特征值(characteristic)

				readServiceId: printerInfo.readServiceId, //  read 操作 蓝牙设备服务的 uuid
				readCharaterId: printerInfo.readCharaterId, //  read 操作 蓝牙设备特征值的 uuid
				writeServiceId: printerInfo.writeServiceId, //  write 操作 蓝牙设备服务的 uuid
				writeCharaterId: printerInfo.writeCharaterId, //  write 操作 蓝牙设备特征值的 uuid
				notifyServiceId: printerInfo.notifyServiceId, //  notify 操作 蓝牙设备服务的 uuid
				notifyCharaterId: printerInfo.notifyCharaterId, //  notify 操作 蓝牙设备特征值的 uuid
				indicateServiceId: printerInfo.indicateServiceId, //  indicate 操作 蓝牙设备服务的 uuid
				indicateCharaterId: printerInfo.indicateCharaterId, //  indicate 操作 蓝牙设备特征值的 uuid
			};
			printerRecord.push(storagePrinterInfo);
		}

		state.printerRecord = printerRecord;
		uni.setStorageSync(PRINTER_RECORD_KEY, printerRecord);
	},
	/** 设置打印机记录 */
	setPrinterRecord: function({
		state,
		commit,
		dispatch
	}, printerRecord) {
		// uni.removeStorageSync(PRINTER_RECORD_KEY);
		state.printerRecord = printerRecord;
		uni.setStorageSync(PRINTER_RECORD_KEY, printerRecord);
	},
	/** 设置打印机信息 */
	setPrinterInfo: function({
		state,
		commit,
		dispatch
	}, printerInfo) {
		// uni.removeStorageSync(PRINTER_INFO_KEY);
		state.printerInfo = printerInfo;
		const storagePrinterInfo = {
			name: printerInfo.name, // (String 类型 )蓝牙设备名称 某些设备可能没有此字段值。
			deviceId: printerInfo.deviceId, //  (String 类型 )蓝牙设备的id
			advertisData: printerInfo.advertisData, //  (ArrayBuffer 类型 )蓝牙设备的广播数据段中的ManufacturerData数据段
			advertisServiceUUIDs: printerInfo
				.advertisServiceUUIDs, //  (Array[String] 类型 )蓝牙设备的广播数据段中的ServiceUUIDs数据段
			localName: printerInfo.localName, //  (String 类型 )蓝牙设备的广播数据段中的LocalName数据段
			serviceData: printerInfo.serviceData, //  (JSON 类型 )蓝牙设备的广播数据段中的ServiceData数据段

			sevices: printerInfo.sevices, //  蓝牙设备所有服务(service)
			characteristics: printerInfo.characteristics, //  蓝牙设备的所有服务的所有特征值(characteristic)

			autoConnect: printerInfo.autoConnect, //  是否自动连接

			readServiceId: printerInfo.readServiceId, //  read 操作 蓝牙设备服务的 uuid
			readCharaterId: printerInfo.readCharaterId, //  read 操作 蓝牙设备特征值的 uuid
			writeServiceId: printerInfo.writeServiceId, //  write 操作 蓝牙设备服务的 uuid
			writeCharaterId: printerInfo.writeCharaterId, //  write 操作 蓝牙设备特征值的 uuid
			notifyServiceId: printerInfo.notifyServiceId, //  notify 操作 蓝牙设备服务的 uuid
			notifyCharaterId: printerInfo.notifyCharaterId, //  notify 操作 蓝牙设备特征值的 uuid
			indicateServiceId: printerInfo.indicateServiceId, //  indicate 操作 蓝牙设备服务的 uuid
			indicateCharaterId: printerInfo.indicateCharaterId, //  indicate 操作 蓝牙设备特征值的 uuid
		};
		uni.setStorageSync(PRINTER_INFO_KEY, storagePrinterInfo);
	},
	/** 设置打印机纸张尺寸(mm) */
	setPrinterPaperSize: function({
		state,
		commit,
		dispatch
	}, paperSize) {
		// uni.removeStorageSync(PRINTER_PAPER_SIZE_KEY);
		state.printerPaperSize = paperSize;
		uni.setStorageSync(PRINTER_PAPER_SIZE_KEY, paperSize);
	},
	/** 设置打印机纸张间距(mm) */
	setPrinterPaperGap: function({
		state,
		commit,
		dispatch
	}, paperGap) {
		// uni.removeStorageSync(PRINTER_PAPER_GAP_KEY);
		state.printerPaperGap = paperGap;
		uni.setStorageSync(PRINTER_PAPER_GAP_KEY, paperGap);
	},
	/** 设置打印机纸张黑标(mm) */
	setPrinterPaperBline: function({
		state,
		commit,
		dispatch
	}, paperBline) {
		// uni.removeStorageSync(PRINTER_PAPER_BLINE_KEY);
		state.printerPaperBline = paperBline;
		uni.setStorageSync(PRINTER_PAPER_BLINE_KEY, paperBline);
	},
	/** 监测蓝牙打印机连接状态 */
	viaPrinterBleState: async function({
		state,
		commit,
		getters,
		dispatch
	}) {
		const {
			t
		} = useI18n();
		//实例化声音  
		const uniAudio = uni.createInnerAudioContext();
		// uniAudio.startTime = 0;	// 开始播放的位置（单位：s），默认 0
		// uniAudio.autoplay = false;	// 是否自动开始播放，默认 false
		// uniAudio.loop = false;	// 是否循环播放，默认 false
		// uniAudio.obeyMuteSwitch = true;	// 是否遵循系统静音开关，当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音，默认值 true
		// 初始化蓝牙模块
		await dispatch('openBluetoothAdapter', 'none');
		// 自动连接监听
		if (state.printerInfo.connected !== true) {
			let time = setTimeout(async () => {
				await offlinePrinterMonitor();

				clearTimeout(time);
			}, 10000);
		}
		// 离线打印机监听器
		async function offlinePrinterMonitor() {
			const printerInfo = getters.getPrinterInfo;
			if (printerInfo && printerInfo.deviceId && printerInfo.connected !== true &&
				printerInfo.autoConnect === true) {
				await dispatch('startBluetoothSearch', {
					callback: async (res) => {
						// console.log('startBluetoothSearch_callback', res);
						const searchedPrinter = res.find(function(value, index, arr) {
							return value.deviceId === printerInfo.deviceId;
						});
						if (searchedPrinter) {
							await dispatch('stopBluetoothSearch', 'none');
							let time = setTimeout(async () => {
								if (state.printerInfo.connected !== true) {
									const connected = await dispatch(
										'connectBlePrinter', {
											printerInfo: searchedPrinter,
											timeout: null,
											mode: 'none'
										});
								}

								clearTimeout(time);
							}, 3000);
						}
					},
					mode: 'none'
				});
			}
		}

		// 监测蓝牙状态
		onBluetoothDeviceState(async function(res) {
			// 该方法回调中可以用于处理连接意外断开等异常情况
			const printerInfo = getters.getPrinterInfo;
			if (printerInfo && printerInfo.deviceId === res.deviceId) {
				state.printerInfo.connected = res.connected;
				// 处理推送消息及连接音效
				let msgTitle = '';
				let msgContent = '';
				if (state.printerInfo.connected === true) {
					uniAudio.src = jarvisConnected;
					msgTitle = t('bluetooth.connectedText');
					msgContent =
						`${t('bluetooth.blePrinterText')} [${printerInfo.name}] ${t('bluetooth.connectedText')}`;
				} else {
					uniAudio.src = jarvisDisconnected;
					msgTitle = t('bluetooth.disconnectedText');
					msgContent =
						`${t('bluetooth.blePrinterText')} [${printerInfo.name}] ${t('bluetooth.disconnectedText')}`;
					if (printerInfo.autoConnect === true) {
						offlinePrinterMonitor();
					}
				}
				// 创建本地消息
				//#ifdef APP-PLUS
				// plus.push.createMessage( content, payload, option );
				let pushMsg = false;
				if (getApp().globalData.appHide === true) {
					pushMsg = true;
				} else {
					const pages = getCurrentPages();
					let currentRoute = '';
					if (pages && pages.length > 0) {
						const currentPage = pages[pages.length - 1];
						if (currentPage.route) {
							currentRoute = currentPage.route;
						}
					}
					if (currentRoute !== 'pages/sys/profile/printerSetup') {
						pushMsg = true;
					}
				}
				if (state.printerInfo.connected === true) {
					pushMsg = false;
				}
				if (pushMsg === true && msgContent !== undefined && msgContent !== null &&
					msgContent !== '') {
					uni.showModal({
						title: msgTitle,
						content: msgContent,
						showCancel: false
					});
					// // content: ( String ) 必选 消息显示的内容，在系统通知中心中显示的文本内容。
					// // payload: ( String ) 可选 消息承载的数据，可根据业务逻辑自定义数据格式。
					// // options: ( MessageOptions ) 可选 创建消息的额外参数，参考MessageOptions。
					// plus.push.createMessage(msgContent, state.printerInfo, {
					// 	cover: true, //是否覆盖上一次提示的消息
					// 	// icon: '@/static/images/logos/logo.png', // 推送消息的图标,
					// 	title: msgTitle, //推送消息的标题
					// });
				}
				//#endif
				// 播放音效
				uniAudio.play();
			}
		});
	},
	/** 连接低功率蓝牙打印机 */
	connectBlePrinter: async function({
		state,
		commit,
		dispatch
	}, {
		printerInfo,
		timeout = null,
		mode = 'message'
	}) {
		let connected = false;
		if (printerInfo) {
			if (printerInfo.deviceId === state.printerInfo.deviceId && state.printerInfo.connected === true) {
				await dispatch('releaseBluetoothDevice', {
					deviceId: printerInfo.deviceId,
					mode: 'none'
				});
			}
			// state.printerInfo = printerInfo;
			// const bindRes = await bindBluetoothDevice(printerInfo.deviceId, timeout, mode);
			const bindRes = await dispatch('bindBluetoothDevice', {
				deviceId: printerInfo.deviceId,
				timeout: timeout,
				mode: mode
			});
			if (bindRes === true) {
				printerInfo.connected = true;
				printerInfo.autoConnect = true;
				// printerInfo.sevices = await getBluetoothSevices(printerInfo.deviceId, mode);
				printerInfo.sevices = await dispatch('getBluetoothSevices', {
					deviceId: printerInfo.deviceId,
					mode: mode
				});
				if (printerInfo.sevices && printerInfo.sevices.length > 0) {
					// printerInfo.characteristics = await getBluetoothCharacteristicsByServices(printerInfo.deviceId, printerInfo.sevices, mode);
					printerInfo.characteristics = await dispatch('getBluetoothCharacteristicsByServices', {
						deviceId: printerInfo.deviceId,
						services: printerInfo.sevices,
						mode: mode
					});
					// uni.showModal({
					// 	title: '特征值',
					// 	content: JSON.stringify(bleCharacteristics)
					// });
					let read = false;
					let write = false;
					let notify = false;
					let indicate = false;
					for (let i = 0; i < printerInfo.characteristics.length; ++i) {
						const characteristic = printerInfo.characteristics[i];
						if (!read) {
							if (characteristic.Read) {
								printerInfo.readServiceId = characteristic.ServiceId;
								printerInfo.readCharaterId = characteristic.CharaterId;
								read = true;
							}
						}
						if (!write) {
							if (characteristic.Write) {
								printerInfo.writeServiceId = characteristic.ServiceId;
								printerInfo.writeCharaterId = characteristic.CharaterId;
								write = true;
							}
						}
						if (!notify) {
							if (characteristic.Notify) {
								printerInfo.notifyServiceId = characteristic.ServiceId;
								printerInfo.notifyCharaterId = characteristic.CharaterId;
								notify = true;
							}
						}
						if (!indicate) {
							if (characteristic.Indicate) {
								printerInfo.indicateServiceId = characteristic.ServiceId;
								printerInfo.indicateCharaterId = characteristic.CharaterId;
								indicate = true;
							}
						}
					}
				}
				// printerInfo.sevices = undefined;
				// // printerInfo.characteristics = undefined;
				// uni.showModal({
				// 	title: '测试',
				// 	content: JSON.stringify(printerInfo)
				// });
				connected = true;
			} else {
				printerInfo.connected = false;
			}
		}
		await dispatch('setPrinterInfo', printerInfo);
		return connected;
	},
	/** 断开连接低功率蓝牙打印机 */
	disconnectBlePrinter: async function({
		state,
		commit,
		dispatch
	}, {
		deviceId,
		mode = 'message'
	}) {
		let printerInfo = state.printerInfo;
		if (deviceId === printerInfo.deviceId && printerInfo.connected === true) {
			// const disconnected = await releaseBluetoothDevice(deviceId);
			const disconnected = await dispatch('releaseBluetoothDevice', {
				deviceId: deviceId,
				mode: mode
			});
			if (disconnected === true) {
				printerInfo.connected = false;
				printerInfo.autoConnect = false;
				await dispatch('setPrinterInfo', printerInfo);
			}
			return disconnected;
		}
		return false;
	},
}
